<template>
  <a-spin :spinning="loading">
    <div class="flex-container">
      <div class="item item1">
        <a-card>
          <a-form-model
            ref="formRef"
            :label-col="{ span: 4 }"
            :model="form"
            :wrapper-col="{ span: 14 }"
            @keyup.enter="loadData"
          >
            <a-form-model-item label="物料名称（品名）" prop="materialName">
              <a-input-search
                v-model:value="form.materialName"
                enter-button
                placehodler="请输入物料名称（品名）"
                @search="loadData"
              />
            </a-form-model-item>
          </a-form-model>
          <a-table
            :columns="columns"
            :dataSource="dataSource"
            :loading="tableLoading"
            :pagination="ipagination"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :scroll="{ x: true }"
            rowKey="id"
            size="middle"
            @change="handleTableChange"
          >
          </a-table>
        </a-card>
      </div>
      <div class="item item2">
        <a-space align="center" direction="vertical" size="large" style="width: 100%;height: 100%">
          <a-button icon="right" size="large" @click="selectRecords"></a-button>
          <a-button icon="left" size="large" @click="deleteRecords"></a-button>
        </a-space>
      </div>
      <div class="item item3">
        <a-card>
          <a-space direction="vertical">
            <slot name="action"></slot>
            <a-table
              :columns="columns"
              :dataSource="selectedData"
              :pagination="selectedIpagination"
              :rowSelection="{ selectedRowKeys: selectedDataRowKeys, onChange: onSelectedDataChange }"
              rowKey="id"
              @change="handleSelectedTableChange"
            >
            </a-table>
          </a-space>
        </a-card>
      </div>
    </div>
  </a-spin>
</template>

<script>
import HfMaterialSearchSelectTag from '@comp/HfManual/HfMaterialSearchSelectTag.vue'
import { getAction } from '@api/manage'

export default {
  name: 'HfBatchSelectTransfer',
  components: { HfMaterialSearchSelectTag },
  props: {
    dataUrl: {
      type: String,
      default: '',
      required: true
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    selectedData(val) {
      this.$emit('change', val)
    }
  },
  data() {
    // this.loadData = debounce(this.loadData, 1200) //消抖
    return {
      form: {
        materialName: ''
      },
      tableLoading: false,
      ipagination: {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total, range) => `共 ${total} 条`,
        position: 'top'
      },
      selectedIpagination: {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total, range) => `共 ${total} 条`,
        position: 'top'
      },
      dataSource: [],
      selectedData: [],
      selectedRowKeys: [],
      selectedDataRowKeys: [],
      selectedDataRows: [],
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 20,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料名称（品名）',
          align: 'center',
          dataIndex: 'materialName',
          width: 200
        },
        {
          title: '品番',
          align: 'center',
          dataIndex: 'saleCode'
        },
        {
          title: 'QAD',
          align: 'center',
          dataIndex: 'qad'
        },
        {
          title: '客户',
          align: 'center',
          dataIndex: 'customId_dictText',
          width: 100
        },
        {
          title: '单箱数',
          align: 'center',
          dataIndex: 'perNumber'
        }
      ]
    }
  },
  computed: {
    existDataIds() {
      return this.selectedData.map(item => item.id)
    }
  },
  methods: {
    loadData() {
      this.tableLoading = true
      getAction(this.dataUrl, {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        materialName: this.form.materialName
      })
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
          }
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onSelectedDataChange(selectedRowKeys, selectionRows) {
      this.selectedDataRowKeys = selectedRowKeys
      this.selectedDataRows = selectionRows
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleSelectedTableChange(pagination, filters, sorter) {
      this.selectedIpagination = pagination
    },
    selectRecords() {
      // 如果已存在就跳过
      let filter = this.selectionRows.filter(item => !this.existDataIds.includes(item.id))
      this.selectedData.push(...filter)
      this.onSelectChange([], [])
    },
    deleteRecords() {
      this.selectedData = this.selectedData.filter(item => !this.selectedDataRowKeys.includes(item.id))
      this.onSelectedDataChange([], [])
    },
    handleReset() {
      this.selectedData = []
    }
  }
}
</script>

<style scoped>
.flex-container {
  display: flex; /* 启用 Flexbox */
  width: 100%; /* 容器宽度占满父级 */
  height: 100%;
  justify-content: center;
  //align-items: center;
}

.item {
  height: 100%; /* 统一高度，可根据需要调整 */
}

.item1,
.item3 {
  flex: 6; /* 占2份 */
}

.item2 {
  flex: 1; /* 占1份 */
}
</style>
